package org.springframework.sandbox.nettymvcpost.nettymvc;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion;

import java.net.URI;
import java.nio.charset.Charset;

public class ByteToFullRequestDecoder extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf content=(ByteBuf) msg;
        Charset charset=Charset.defaultCharset();
        String input=content.toString(charset);

        RequestFuture requestFuture= JSONObject.parseObject(input, RequestFuture.class);

        //URI uri=new URI("/getUserNameById");
        String[] patharray=requestFuture.getPath().split("\\.");
        String path= patharray[patharray.length-1];
        URI uri=new URI("/"+path+"extPost"+"?userId="+requestFuture.getRequest().toString());

        NettyMessage nettyMessage=new NettyMessage();
        nettyMessage.setObjectbody(content);
        byte [] bytesinfo;
        if(content!=null){
            bytesinfo=new byte[content.readableBytes()];
            content.getBytes(0,bytesinfo);
            nettyMessage.setBytesbody(bytesinfo);
        }
        FullHttpRequest fullHttpRequest=new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,uri.toASCIIString());
        /*fullHttpRequest.content().readBytes(content);
        content.release();*/
        nettyMessage.setFullHttpRequest(fullHttpRequest);
        //ByteBuf byteBuf= fullHttpRequest.content();

        //channelHandlerContext.write(fullHttpRequest);
        //ctx.fireChannelRead(fullHttpRequest);
        ctx.fireChannelRead(nettyMessage);

    }
}
